/*
 * @Author: fisher
 * @Date: 2024-02-26 11:13:12
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-03-08 10:09:56
 * @FilePath: \allback\controllers\ueinstanceController.js
 * @Description:
 */
// controllers/ueInstanceController.js
const ueInstanceService = require('../services/ueinstanceService')
const dayjs = require('dayjs')
const createInstance = async ctx => {
  const data = ctx.request.body
  try {
    const instance = await ueInstanceService.createInstance(data)
    ctx.status = 200
    ctx.body = {
      status: true,
      message: '实例创建成功！',
      data: instance
    }
  } catch (error) {
    throw new HttpError(error.message, 400)
  }
}

const getInstanceById = async ctx => {
  const { id } = ctx.query
  try {
    const instance = await ueInstanceService.getInstanceById(id)
    if (instance) {
      ctx.status = 200
      ctx.body = {
        status: true,
        message: '获取实例成功！',
        data: instance
      }
    } else {
      ctx.status = 404
      ctx.body = {
        status: false,
        message: '未查询到实例！'
      }
    }
  } catch (error) {
    throw new HttpError(error.message, 400)
  }
}

const getInstanceList = async ctx => {
  const { pageSize, pageNo, search } = ctx.request.body
  try {
    const { records, total } = await ueInstanceService.getInstanceList(
      pageSize,
      pageNo,
      search
    )
    ctx.status = 200
    ctx.body = {
      status: true,
      message: '获取实例列表成功！',
      data: records,
      page: {
        total: total,
        pageNo: pageNo,
        pages: Math.ceil(total / pageSize)
      }
    }
  } catch (error) {
    throw new HttpError(error.message, 400)
  }
}

const updateInstance = async ctx => {
  const data = ctx.request.body
  try {
    const updatedInstance = await ueInstanceService.updateInstanceById(
      data.id,
      data
    )
    if (updatedInstance) {
      ctx.status = 200
      ctx.body = {
        status: true,
        message: '更新实例成功！',
        data: updatedInstance
      }
    } else {
      ctx.status = 404
      ctx.body = {
        status: false,
        message: '更新实例失败！'
      }
    }
  } catch (error) {
    throw new HttpError(error.message, 400)
  }
}

const deleteInstance = async ctx => {
  const { ids } = ctx.request.body
  try {
    await ueInstanceService.deleteInstance(ids)
    ctx.status = 200
    ctx.body = {
      status: true,
      message: '删除实例成功！'
    }
  } catch (error) {
    throw new HttpError(error.message, 400)
  }
}

const startInstances = async ctx => {
  const { ids } = ctx.request.body
  try {
    await ueInstanceService.startInstances(ids)
    ctx.status = 200
    ctx.body = {
      status: true,
      message: '启动实例成功！'
    }
  } catch (error) {
    throw new HttpError(error.message, 400)
  }
}

const stopInstances = async ctx => {
  const { ids } = ctx.request.body
  try {
    await ueInstanceService.stopInstances(ids)
    ctx.status = 200
    ctx.body = {
      status: true,
      message: '停止所选实例成功！'
    }
  } catch (error) {
    throw new HttpError(error.message, 400)
  }
}

// const stopInstanceByid = async ctx => {
//   const { id } = ctx.request.body
//   try {
//     await ueInstanceService.stopInstanceByid(id)
//     ctx.status = 200
//     ctx.body = {
//       status: true,
//       message: `停止id:${id}实例成功！`
//     }
//   } catch (error) {
//     throw new HttpError('停止失败，请联系运维人员手动停止！', 400)
//   }
// }

const getInstanceStatus = async ctx => {
  try {
    const status = await ueInstanceService.getInstanceStatus()
    const essentialInfo = JSON.parse(status).map(process => ({
      pm_id: process.pm_id,
      name: process.name,
      status: process.pm2_env.status,
      update: dayjs(parseInt(process.pm2_env.pm_uptime)).format(
        'YYYY-MM-DD HH:mm:ss'
      )
      //查看所有状态
      // data: process
    }))
    ctx.status = 200
    ctx.body = {
      status: true,
      message: `获取实例状态成功！`,
      data: essentialInfo
    }
  } catch (error) {
    throw new HttpError(error.message, 400)
  }
}
const applyForConnect = async ctx => {
  // 提供ue工程id，和用户信息
  const { projectId, connectUserId, connectUserName, connectHost } =
    ctx.request.body
  try {
    const essentialInfo = await ueInstanceService.applyForConnect(
      projectId,
      connectUserId,
      connectUserName,
      connectHost
      // connect
    )
    ctx.status = 200
    ctx.body = {
      status: true,
      message: `获取实例状态成功！`,
      data: essentialInfo
    }
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}

const msgBySignal = async ctx => {
  const {
    instanceId,
    userId,
    playerId,
    clientIp,
    signalHost,
    signalPort,
    useHttps,
    connectStatus
  } = ctx.request.body
  try {
    await ueInstanceService.msgBySignal(
      instanceId,
      userId,
      playerId,
      clientIp,
      signalHost,
      signalPort,
      useHttps,
      connectStatus
    )
    ctx.status = 200
    ctx.body = {
      status: true,
      message: '信令服务器收到消息!'
    }
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}

const closeClient = async ctx => {
  const { instanceId, connectionId } = ctx.request.body
  try {
    await ueInstanceService.closeClient(instanceId, connectionId)
    ctx.status = 200
    ctx.body = {
      status: true,
      message: '关闭连接成功!'
    }
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}
module.exports = {
  createInstance,
  getInstanceById,
  getInstanceList,
  updateInstance,
  deleteInstance,
  startInstances,
  stopInstances,
  // stopInstanceByid,
  getInstanceStatus,
  applyForConnect,
  msgBySignal,
  closeClient
}
